package com.zimi.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zimi.mapper.*;
import com.zimi.model.*;
import com.zimi.util.FormElementUtil;
import com.zimi.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Auther: lmc
 * @Date: 2019/3/29 10:25
 * @Description:
 */
@Service
public class WfWorkflowApplicationService {
    // 定义常量
    private final String ELEMENT_TEXT = "text";
    private final String ELEMENT_HIDDEN = "hidden";
    private final String ELEMENT_SELECT = "combox";
    private final String ELEMENT_CHECKBOX = "checkbox";
    private final String ELEMENT_RADIO = "radio";
    private final String ELEMENT_TEXTAREA = "textarea";
    private final String ELEMENT_DATE = "date";
    private final String ELEMENT_DATETIME = "datetime";
    private final String ELEMENT_NUMBER = "number";
    private final String ELEMENT_IMG = "img";
    private final String ELEMENT_FILE = "file";
    private final String ELEMENT_TABLE = "datagrid";
    private final String ELEMENT_TODOUSER = "todouser";
    private final String ELEMENT_NAME = "name";
    private final String ELEMENT_DISPLAY_NAME = "cn-name";
    private final String ELEMENT_TYPE = "ext-type";
    private final String ELEMENT_VALUE = "dic-value";
    private final String ELEMENT_DICT_ATTR = "dict-attr"; // 表单自定义字段，以 dict-attr = "｛K：V，｝" 方式使用
    private final String ELEMENT_STARTVALUE = "value";
    private final String ELEMENT_DEFAULT_VALUE = "default-value";
    private final String ELEMENT_VERIFY = "lay-verify";
    private final String ELEMENT_REQUIRED = "if-required";
    private final String ELEMENT_EDIT = "can-edit";
    private final String ELEMENT_VIEW = "can-view";
    private final String ELEMENT_SHOW = "default-show";
    private final String ELEMENT_HIDE = "if-hide";
    private final String ELEMENT_BINDING_EVENT = "bind-event";
    private final String ELEMENT_CLICK = "click-event";
    private final String ELEMENT_COLS = "cols";
    private final String ELEMENT_PAGE = "page";
    private final String ELEMENT_PAGESIZE = "pagesize";
    private final String ELEMENT_LIMITS = "limits";
    private final String ELEMENT_OBJTYPE = "obj-type";
    private final String ELEMENT_OPINION = "opinion";
    private final String ELEMENT_Class = "class";
    @Autowired
    private SysCodeMapper sysCodeMapper;
    @Autowired
    private WfFormMapper wfFormMapper;
    @Autowired
    private WfDictionaryMapper wfDictionaryMapper;
    @Autowired
    private WfWorkflowMapper wfWorkflowMapper;
    @Autowired
    private WfActivityMapper wfActivityMapper;
    @Autowired
    private WfTaskMapper wfTaskMapper;
    @Autowired
    private WfSystaskMapper wfSystaskMapper;
    @Autowired
    private WfSystaskKeyMapper wfSystaskKeyMapper;

    /**
     * 获取指定正则式的值
     */
    private static String getString(String str, String regx) {
        //1.将正在表达式封装成对象Patten 类来实现
        Pattern pattern = Pattern.compile(regx);
        //2.将字符串和正则表达式相关联
        Matcher matcher = pattern.matcher(str);
        //3.String 对象中的matches 方法就是通过这个Matcher和pattern来实现的。

        String result;
        //查找符合规则的子串
        if (matcher.find()) {
            //获取 字符串
            result = matcher.group();
            //获取的字符串的首位置和末位置
            //System.out.println(matcher.start()+"--"+matcher.end());
        } else {
            result = "";
        }

        return result;
    }

    /**
     * 获取指定流程，活动的HTML内容
     */
    public String getInstanceHtml(WfWorkflowInstance wfWorkflowInstance, Integer baseTaskId) {
        // 1.取得systask信息
//        Map valueMap = null;
        List<FormElement> arrFormElement = new ArrayList<FormElement>();

        if (wfWorkflowInstance == null) {
            WfSystaskKey wfSystaskKey = wfSystaskKeyMapper.selectByPrimaryKey(baseTaskId);
            if (wfSystaskKey != null) {
                wfWorkflowInstance = new WfWorkflowInstance();
                wfWorkflowInstance.setWfId(wfSystaskKey.getWfId());
                wfWorkflowInstance.setTaskId(wfSystaskKey.getCurrentSysTaskId());
                wfWorkflowInstance.setActivityId(0);
                wfWorkflowInstance.setEditFlag(0);
            }
        }

        if (wfWorkflowInstance != null && wfWorkflowInstance.getTaskId() != null) {
            SysUser sysUser = UserUtil.getUser();

            WfSystask sysTask = wfSystaskMapper.selectByPrimaryKey(wfWorkflowInstance.getTaskId());
            WfTask wfTask = new WfTask();
            if (sysTask != null) {
                wfTask.setTaskExecutor(sysUser.getId());
                wfTask.setSysTaskId(sysTask.getId());

                List<WfTask> listTodo = wfTaskMapper.selectAll(wfTask);
                if (listTodo.size() == 1 && (listTodo.get(0).getWfTaskRecord() != null && listTodo.get(0).getWfTaskRecord() != "")) {
                    arrFormElement = FormElementUtil.getDbFormElements(listTodo.get(0).getWfTaskRecord());
                } else {
                    arrFormElement = FormElementUtil.getDbFormElements(sysTask.getSysTaskRecord());
                }
            }

//            valueMap = wfNextActivityService.analysisJson(sysTask.getWfRecord());
        }

        // 2.取得HTML信息
        int wfId = 0;
        if (wfWorkflowInstance != null && wfWorkflowInstance.getWfId() != null) {
            wfId = wfWorkflowInstance.getWfId();
        }
        WfWorkflow wfWorkflow = wfWorkflowMapper.selectByPrimaryKey(wfId);

        if (wfWorkflow == null) return "";

        WfForm form = wfFormMapper.selectByPrimaryKey(wfWorkflow.getFormEditId());

        if (form != null) {
            if (form.getFormHtml() != null && form.getFormHtml().length() > 0) {
                // 3.取出<input ...>标签内容
                List<String> inputTagList = this.getStrings(form.getFormHtml(), "<input[^>]*>");

                // 4.保存在Map里以备替换
                Map<String, String> inputTagMap = new HashMap<>();
                String elementDefaultValue = null;
                for (String inpuTag : inputTagList) {
                    // 4.设置替换前后的标签信息
                    inputTagMap.put(inpuTag, toChangeInputTag(wfWorkflowInstance.getActivityId(), inpuTag, wfWorkflowInstance.getEditFlag(), arrFormElement));
                }

                // 5.对HTML进行<input ...>标签内容进行替换
                String tmpString = form.getFormHtml();
                for (String key : inputTagMap.keySet()) {
                    tmpString = tmpString.replace(key, inputTagMap.get(key));
                }

                // 添加隐藏情报和按钮
                if (wfWorkflowInstance.getEditFlag() > 0) {
                    WfActivity wfActivity = wfActivityMapper.selectByPrimaryKey(wfWorkflowInstance.getActivityId());
                    if (wfActivity != null && wfActivity.getActivityCode().equals("001")) {
                        tmpString = String.format(" <div %s><div class=\"layui-form-item\"><div id=\"diy\"></div><div class=\"layui-input-block\" style=\"margin-right: 30px;\">%s<button type=\"button\" class=\"layui-btn\" id=\"selectWF\" >查看流程</button>%s</div></div></div><div style=\"height:80px\"></div>%s", "style=\"width:100%;text-align:right;height:50px;background:#e6e6e6;position:fixed;top:0;padding-top:10px;z-index:99;\"", getHiddernTag(wfWorkflowInstance, arrFormElement), getButtonInfo(wfWorkflowInstance), tmpString);
                    } else if (wfActivity != null && wfActivity.getActivityCode().equals("end")) {
                        tmpString = String.format(" <div %s><div class=\"layui-form-item\"><div id=\"diy\"></div><div class=\"layui-input-block\" style=\"margin-right: 30px;\">%s<button type=\"button\" class=\"layui-btn\" id=\"closeWF\" >关闭</button></div></div></div><div style=\"height:80px\"></div>%s", "style=\"width:100%;text-align:right;height:50px;background:#e6e6e6;position:fixed;top:0;padding-top:10px;z-index:99;\"", getHiddernTag(wfWorkflowInstance, arrFormElement), tmpString);
                    } else {
                        tmpString = String.format(" <div %s><div class=\"layui-form-item\"><div id=\"diy\"></div><div class=\"layui-input-block\" style=\"margin-right: 30px;\">%s %s</div></div></div><div style=\"height:80px\"></div>%s", "style=\"width:100%;text-align:right;height:50px;background:#e6e6e6;position:fixed;top:0;padding-top:10px;z-index:99;\"", getHiddernTag(wfWorkflowInstance, arrFormElement), getButtonInfo(wfWorkflowInstance), tmpString);
                    }

                }
                if (wfWorkflowInstance.getEditFlag() == 0) {
                    tmpString = String.format(" <div class=\"layui-form-item\"><div>%s</div></div>%s", getHiddernTag(wfWorkflowInstance, arrFormElement), tmpString);
                }
                form.setFormHtml(tmpString);

            }
        }

        return form.getFormHtml();
    }

    /*
     * @author: wj
     * @description: 取得Html画面标签并返回List<FormItem>
     * @date: 2019/3/30 11:36
     * @param
     * @return
     */
    public List<WfFormItem> getFormItems(String htmlContent) throws Exception {
        List<WfFormItem> result = new ArrayList<>();

        if (htmlContent != null && htmlContent.length() > 0) {
            // 1.取出<input ...>标签内容
            List<String> inputTagList = this.getStrings(htmlContent, "<input[^>]*>");

            WfFormItem formItem = null;
            List<CandidateValue> value = null;
            CandidateValue candidateValue = null;
            List<WfDictionary> sysCodeList = null;
            WfDictionary wfDictionary = null;

            // 2.取出<input ...>标签的name，ext-type，value
            for (String inputElement : inputTagList) {
                formItem = new WfFormItem();

                formItem.setName(this.getDoubleQuotationValue(this.getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_NAME)))));
                formItem.setDisplayName(this.getDoubleQuotationValue(this.getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_DISPLAY_NAME)))));
                formItem.setType(this.getDoubleQuotationValue(this.getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_TYPE)))));

                String elementVal = this.getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_VALUE))));
                value = new ArrayList<>();
                if (elementVal.length() > 0) {
                    wfDictionary = new WfDictionary();
                    wfDictionary.setParentId(elementVal);
                    sysCodeList = wfDictionaryMapper.selectAll(wfDictionary);

                    // 把父节点信息删除
                    for (WfDictionary wd : sysCodeList) {
                        candidateValue = new CandidateValue();
                        candidateValue.setValue(wd.getValue());
                        candidateValue.setDisplayName(wd.getCnName());

                        value.add(candidateValue);
                    }
                }

                formItem.setValue(value);

                result.add(formItem);
            }
        }

        return result;
    }

    /**
     * 获取改变后的<input ...>标签值
     */
    private String toChangeInputTag(Integer activityId, String inputElement, int editFlag, List<FormElement> arrFormElement) {
        WfActivity wfActivity = wfActivityMapper.selectByPrimaryKey(activityId);
        if (wfActivity != null) {
            if (wfActivity.getActivityCode().equals("end")) {
                editFlag = 0;
            }
        }

        final String REQUIRED_TRUE = "true";
        final String REQUIRED_CONTENT = "required";
        String result = "";
        StringBuffer stringBuffer = null;
        final String DEFAULT_FUNCTION = "defaultFunction";
        String disableMark = "";
        String phText = "";
        String tempValue = "";
        String tempValueCode = "";
        String checkedMark = "";
        String displayMark = null;
        List<String> tempValues = new ArrayList<>();
        List<String> tempValueCodes = new ArrayList<>();
        String[] tempStr = null;
        String elementType = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_TYPE))));
        String elementVerify = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_VERIFY))));
        String elementValue = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_VALUE))));
        String elementStartValue = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_STARTVALUE))));
        String elementName = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_NAME))));
        String elementClass = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_Class))));
        elementClass = elementClass.replace("ln-sel-input", "");
        String elementDisplayName = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_DISPLAY_NAME))));
        String elementDefaultValue = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_DEFAULT_VALUE))));
        String elementBindingData = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_BINDING_EVENT))));
        String elementClick = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_CLICK))));
        String cols = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_COLS))));
        String tempObjType = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_OBJTYPE))));
        String opinion = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_OPINION))));
        String elementDictAttr = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_DICT_ATTR))));

//        String page = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_PAGE))));
//        String pageSize = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_PAGESIZE))));
//        String limits = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_LIMITS))));
        boolean isEdit = false;
        if (editFlag > 0) {
            isEdit = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_EDIT)))).indexOf(activityId + "") >= 0 ? true : false;
        } else if (editFlag == 0) {
            isEdit = false;
        }
        boolean isView = true;
        if (editFlag > 0)
            isView = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_VIEW)))).indexOf(activityId + "") >= 0 ? true : false;
        boolean isShow = false;
        if (editFlag > 0)
            isShow = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_SHOW)))).indexOf(activityId + "") >= 0 ? true : false;
        boolean isHide = false;
        if (editFlag > 0)
            isHide = getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_HIDE)))).indexOf(activityId + "") >= 0 ? true : false;
        boolean isRquired = REQUIRED_TRUE.equals(getDoubleQuotationValue(getString(inputElement, String.format(String.format("%s[ |=]\"(.*?)\"", ELEMENT_REQUIRED))))) ? true : false;

        if (isRquired) {
            if (elementVerify == "") {
                elementVerify = "required";
            } else {
                elementVerify += " | required";
            }
        }

        String requiredValue = null;
        Map<String, FormElement> mapFormElement = new HashMap<String, FormElement>();


        //把db存的element json<List> 转为map
        if (arrFormElement != null && arrFormElement.size() > 0) {
            for (FormElement formElement : arrFormElement) {
                mapFormElement.put(formElement.getName(), formElement);
            }
        }

        if (!isEdit) {
            disableMark = "disabled";
            phText = "";
        } else {
            phText = "请输入" + elementDisplayName;
        }

        if (isView) {
            displayMark = "";
        } else {
            displayMark = "none";
        }

        if (mapFormElement.size() > 0 && mapFormElement.get(elementName) != null) {
            tempValues = mapFormElement.get(elementName).getValues();
        }
        tempValue = tempValues.size() > 0 ? tempValues.get(0) : "";
        tempValue = tempValue.replace("\"","&quot;");
        if (mapFormElement.size() > 0 && mapFormElement.get(elementName) != null) {
            tempValueCodes = mapFormElement.get(elementName).getValueCodes();
        }
        tempValueCode = tempValueCodes.size() > 0 ? tempValueCodes.get(0) : "";
//        if (mapFormElement.size() > 0 && mapFormElement.get(elementName) != null) tempObjType = mapFormElement.get(elementName).getObjType()!=null ? mapFormElement.get(elementName).getObjType() : "";

        switch (elementType) {
            case ELEMENT_HIDDEN:
                result = String.format("<input ext-type=\"%s\" name=\"%s\" lay-filter=\"%s\" cn-name=\"%s\" class=\"layui-input %s\" type=\"hidden\" value=\"%s\" dict-attr=\"%s\">", elementType, elementName, elementName, elementDisplayName, elementClass, elementStartValue, elementDictAttr);
                break;
            case ELEMENT_TEXT:
                if (tempObjType.equals("opinion")) {
                    result = String.format("<input ext-type=\"%s\" name=\"%s\" lay-filter=\"%s\" cn-name=\"%s\" class=\"layui-input %s\" type=\"text\" placeholder=\"%s\" autocomplete=\"off\" lay-verify=\"%s\" value=\"%s\" %s value-code=\"%s\" obj-type=\"%s\" style=\"display:%s;\" default-value=\"%s\" click-event=\"%s\" dict-attr=\"%s\">", elementType, elementName, elementName, elementDisplayName, elementClass, phText, elementVerify, tempValue, disableMark, tempValueCode, tempObjType, displayMark, isShow ? elementDefaultValue : "", elementClick, elementDictAttr);
                } else {
                    result = String.format("<input ext-type=\"%s\" name=\"%s\" lay-filter=\"%s\" cn-name=\"%s\" class=\"layui-input %s\" type=\"text\" placeholder=\"%s\" autocomplete=\"off\" lay-verify=\"%s\" value=\"%s\" %s value-code=\"%s\" style=\"display:%s;\" default-value=\"%s\" click-event=\"%s\" dict-attr=\"%s\">", elementType, elementName, elementName, elementDisplayName, elementClass, phText, elementVerify, tempValue, disableMark, tempValueCode, displayMark, isShow ? elementDefaultValue : "", elementClick, elementDictAttr);
                }
                break;
            case ELEMENT_DATE:
                result = String.format("<input ext-type=\"%s\" type=\"text\" name=\"%s\" lay-filter=\"%s\" cn-name=\"%s\" placeholder=\"\" autocomplete=\"off\" class=\"layui-input\" lay-verify=\"%s\" value=\"%s\" %s style=\"display:%s;\" default-value=\"%s\" click-event=\"%s\" dict-attr=\"%s\">", elementType, elementName, elementName, elementDisplayName, isRquired ? "|" + REQUIRED_CONTENT : "", tempValue, disableMark, displayMark, isShow ? elementDefaultValue : "", elementClick, elementDictAttr);
                break;
            case ELEMENT_DATETIME:
                if (tempObjType.equals("opinion")) {
                    result = String.format("<input ext-type=\"%s\" type=\"text\" name=\"%s\" lay-filter=\"%s\" cn-name=\"%s\" placeholder=\"\" autocomplete=\"off\" class=\"layui-input\" lay-verify=\"%s\" value=\"%s\" %s style=\"display:%s;\" obj-type=\"%s\" default-value=\"%s\" click-event=\"%s\" dict-attr=\"%s\">", elementType, elementName, elementName, elementDisplayName, isRquired ? "|" + REQUIRED_CONTENT : "", tempValue, disableMark, displayMark, tempObjType, isShow ? elementDefaultValue : "", elementClick, elementDictAttr);
                } else {
                    result = String.format("<input ext-type=\"%s\" type=\"text\" name=\"%s\" lay-filter=\"%s\" cn-name=\"%s\" placeholder=\"\" autocomplete=\"off\" class=\"layui-input\" lay-verify=\"%s\" value=\"%s\" %s style=\"display:%s;\" default-value=\"%s\" click-event=\"%s\" dict-attr=\"%s\">", elementType, elementName, elementName, elementDisplayName, isRquired ? "|" + REQUIRED_CONTENT : "", tempValue, disableMark, displayMark, isShow ? elementDefaultValue : "", elementClick, elementDictAttr);
                }
                break;
            case ELEMENT_NUMBER:
                result = String.format("<input ext-type=\"%s\" min=\"0\" type=\"number\" name=\"%s\" lay-filter=\"%s\" cn-name=\"%s\" autocomplete=\"off\" class=\"layui-input %s\" lay-verify=\"%s\" value=\"%s\" %s style=\"display:%s;\" default-value=\"%s\" click-event=\"%s\" dict-attr=\"%s\">", elementType, elementName, elementName, elementDisplayName, elementClass, isRquired ? "|" + REQUIRED_CONTENT : "", tempValue, disableMark, displayMark, isShow ? elementDefaultValue : "", elementClick, elementDictAttr, elementDictAttr);
                break;
            case ELEMENT_SELECT:
                stringBuffer = new StringBuffer();

                stringBuffer.append(String.format("<select name=\"%s\" lay-filter=\"%s\" cn-name=\"%s\" lay-verify=\"%s\" %s dic-value=\"%s\" style=\"display:%s;\" binding-data=\"%s\" value-code=\"%s\" click-event=\"%s\" dict-attr=\"%s\">", elementName, elementName, elementDisplayName, elementVerify, disableMark, elementValue, displayMark, elementBindingData, tempValueCode, elementClick, elementDictAttr));
                if (elementBindingData == "") {
                    stringBuffer.append("<option value=\"\"></option>");
                    for (WfDictionary wd : this.getSysCodes(elementValue)) {
//                        stringBuffer.append(String.format("<option value=\"%s\" %s>%s</option>", String.format("%s:%s", wd.getValue(), wd.getCnName()), wd.getValue().equals(String.format("%s:%s", tempValueCode, tempValue)) ? "selected=\"\"" : "", wd.getCnName()));
                        Boolean flag = true;
                        for (String val : tempValueCodes) {
                            if (val == wd.getValue() || val.equals(wd.getValue())) {
                                flag = false;
                            }
                        }
                        if (flag) {
                            stringBuffer.append(String.format("<option value=\"%s\" %s>%s</option>", String.format("%s:%s", wd.getValue(), wd.getCnName()), "", wd.getCnName()));
                        } else {
                            stringBuffer.append(String.format("<option value=\"%s\" %s>%s</option>", String.format("%s:%s", wd.getValue(), wd.getCnName()), "selected=\"selected\"", wd.getCnName()));
                        }
                    }
                }

                stringBuffer.append("</select>");
                result = stringBuffer.toString();
                break;
            case ELEMENT_CHECKBOX:
                stringBuffer = new StringBuffer();
                for (WfDictionary wd : this.getSysCodes(elementValue)) {
                    checkedMark = "";
                    if (tempValueCodes.size() > 0) {
                        for (String valueCode : tempValueCodes) {
                            if (wd.getValue().equals(valueCode)) {
                                checkedMark = "checked";
                                break;
                            }
                        }
                    }

                    stringBuffer.append(String.format("<input type=\"checkbox\" name=\"%s\" lay-filter=\"%s\" cn-name=\"%s\" value=\"%s\" title=\"%s\" %s %s dic-value=\"%s\" style=\"display:%s;\" click-event=\"%s\" dict-attr=\"%s\">", elementName, elementName, elementDisplayName, String.format("%s:%s", wd.getValue(), wd.getCnName()), wd.getCnName(), checkedMark, disableMark, elementValue, displayMark, elementClick, elementDictAttr));
                }
                result = stringBuffer.toString();
                break;
            case ELEMENT_RADIO:
                stringBuffer = new StringBuffer();
                for (WfDictionary wd : this.getSysCodes(elementValue)) {
//                    if (tempValueCode == "") {
                    if (tempObjType.equals("opinion")) {
                        stringBuffer.append(String.format("<input name=\"%s\" lay-filter=\"%s\" cn-name=\"%s\" type=\"radio\" value=\"%s\" title=\"%s\" %s %s dic-value=\"%s\" style=\"display:%s;\" obj-type=\"%s\" click-event=\"%s\" dict-attr=\"%s\">", elementName, elementName, elementDisplayName, String.format("%s:%s", wd.getValue(), wd.getCnName()), wd.getCnName(), wd.getValue().equals(tempValueCode) ? "checked" : "", disableMark, elementValue, displayMark, tempObjType, elementClick, elementDictAttr));
                    } else {
                        stringBuffer.append(String.format("<input name=\"%s\" lay-filter=\"%s\" cn-name=\"%s\" type=\"radio\" value=\"%s\" title=\"%s\" %s %s dic-value=\"%s\" style=\"display:%s;\" click-event=\"%s\" dict-attr=\"%s\">", elementName, elementName, elementDisplayName, String.format("%s:%s", wd.getValue(), wd.getCnName()), wd.getCnName(), wd.getValue().equals(tempValueCode) ? "checked" : "", disableMark, elementValue, displayMark, elementClick, elementDictAttr));
                    }
//                    } else {
//                        if (wd.getValue().equals(tempValueCode)) {
//                            stringBuffer.append(String.format("<input name=\"%s\" cn-name=\"%s\" type=\"radio\" value=\"%s\" title=\"%s\" %s %s dic-value=\"%s\" style=\"display:%s;\" obj-type=\"%s\"  click-event=\"%s\">", elementName, elementDisplayName, String.format("%s:%s", wd.getValue(), wd.getCnName()), wd.getCnName(),wd.getValue().equals(tempValueCode) ? "checked" : "", disableMark, elementValue, displayMark, tempObjType, elementClick));
//                        }
//                    }
                }

                result = stringBuffer.toString();
                break;
            case ELEMENT_TEXTAREA:
                if (tempObjType.equals("opinion")) {
                    result = String.format("<textarea ext-type=\"%s\" name=\"%s\" lay-filter=\"%s\" cn-name=\"%s\" class=\"layui-textarea\" placeholder=\"%s\" lay-verify=\"%s\" %s style=\"display:%s;\" obj-type=\"%s\"  click-event=\"%s\" dict-attr=\"%s\">%s</textarea>", elementType, elementName, elementName, elementDisplayName, phText, isRquired ? REQUIRED_CONTENT : "", disableMark, displayMark, tempObjType, elementClick, elementDictAttr, tempValue);
                } else {
                    result = String.format("<textarea ext-type=\"%s\" name=\"%s\" lay-filter=\"%s\" cn-name=\"%s\" class=\"layui-textarea\" placeholder=\"%s\" lay-verify=\"%s\" %s style=\"display:%s;\" click-event=\"%s\" dict-attr=\"%s\">%s</textarea>", elementType, elementName, elementName, elementDisplayName, phText, isRquired ? REQUIRED_CONTENT : "", disableMark, displayMark, elementClick, elementDictAttr, tempValue);
                }
                break;
            case ELEMENT_IMG:
                result = String.format("<button ext-type=\"%s\" name=\"%s\" cn-name=\"%s\" placeholder=\"%s\" lay-verify=\"%s\" %s style=\"display:%s;\" type=\"button\" class=\"layui-btn\" id=\"%s\" onclick=\"uploadImg(this)\" value=\'%s\' dict-attr=\"%s\">上传图片</button>", elementType, elementName, elementDisplayName, phText, isRquired ? REQUIRED_CONTENT : "", disableMark, displayMark, elementName, tempValues, elementDictAttr);
                break;
            case ELEMENT_FILE:
                result = String.format("<button ext-type=\"%s\" name=\"%s\" lay-filter=\"%s\" cn-name=\"%s\" placeholder=\"%s\" lay-verify=\"%s\" %s style=\"display:%s;\" type=\"button\" class=\"layui-btn\" id=\"%s\" onclick=\"uploadFile(this)\" value=\'%s\' dict-attr=\"%s\"><i class=\"layui-icon\">\uE67C</i>上传文件</button>", elementType, elementName, elementName, elementDisplayName, phText, isRquired ? REQUIRED_CONTENT : "", disableMark, displayMark, elementName, tempValues, elementDictAttr);
                break;
            case ELEMENT_TABLE:
//                result = String.format("<table class=\"layui-hide\" ext-type=\"%s\" name=\"%s\" cn-name=\"%s\" id=\"%s\" lay-filter=\"%s\" cols=\"%s\" page=\"%s\" pageSize=\"%s\" limits=\"%s\" ></table>", elementType, elementName, elementDisplayName, elementName, elementName, cols, page, pageSize, limits );
                result = String.format("<table class=\"layui-hide\" ext-type=\"%s\" name=\"%s\" lay-filter=\"%s\" cn-name=\"%s\" id=\"%s\" lay-filter=\"%s\" cols=\"%s\" value=\"%s\" %s dict-attr=\"%s\"></table>", elementType, elementName, elementName, elementDisplayName, elementName, elementName, cols, tempValue, disableMark, elementDictAttr);
                break;
            case ELEMENT_TODOUSER:
                result = String.format("<input ext-type=\"%s\" name=\"%s\" cn-name=\"%s\" class=\"layui-input\" type=\"text\" placeholder=\"%s\" autocomplete=\"off\" lay-verify=\"%s\" value=\"%s\" %s value-code=\"%s\" obj-type=\"%s\" style=\"display:%s;\" default-value=\"%s\" click-event=\"%s\" dict-attr=\"%s\">", elementType, elementName, elementDisplayName, phText, elementVerify, tempValue, disableMark, tempValueCode, tempObjType, displayMark, isShow ? elementDefaultValue : "", elementClick, elementDictAttr);
                break;
        }

        String resultOutput = String.format("<span style=\"display:%s;\" dict-attr=\"%s\">%s</span>", isView ? "" : "none", elementDictAttr, result);

        //不可编辑环节，不渲染 default-value"
        if ((elementDefaultValue != null && elementDefaultValue != "") && !isShow) {
            resultOutput = resultOutput.replace("default-value", "notnow");
        }

//        required
        //不可编辑环节，不渲染 required
        if (!isEdit) {
            resultOutput = resultOutput.replace("required", "");
        }
        return resultOutput;
    }

    /**
     * 设置流程按钮
     */
    private String getButtonInfo(WfWorkflowInstance wfWorkflowInstance) {
        final String ACTION_TYPE = "liuchenganniuleixing";

        final String ACTION_SAVE = "20";
        final String ACTION_SUBMIT = "10";
        final String ACTION_REVOKE = "50";
        final String ACTION_GOTO = "40";
        final String ACTION_BACK = "30";

        final String SAVE_BUTTON = "save";
        final String SUBMIT_BUTTON = "submit";
        final String REVOKE_BUTTON = "revoke";
        final String GOTO_BUTTON = "goto";
        final String BACK_BUTTON = "back";

        StringBuffer result = new StringBuffer();
        WfActivity wfActivity = wfActivityMapper.selectByPrimaryKey(wfWorkflowInstance.getActivityId());

        String tempString = null;
        String title = "";
        boolean isHaveProvilige = false;

        // 取得流程按钮类型并保存到HashMap里
        SysCode sysCode = new SysCode();
        sysCode.setCodeTypeName(ACTION_TYPE);

        List<SysCode> sysCodeList = sysCodeMapper.selectList(new QueryWrapper<SysCode>(sysCode));
        Map<String, String> actionTypeMap = new HashMap<>();

        for (SysCode sc : sysCodeList) {
            actionTypeMap.put(sc.getCodeValue().toString(), sc.getCodeName());
        }

        if (wfActivity != null && wfActivity.getActivityButtons() != null && wfActivity.getActivityButtons().length() > 0) {
            String[] buttons = wfActivity.getActivityButtons().split(",");
            if (buttons.length > 0) {
                Arrays.sort(buttons);
            }
            for (String tmpButton : buttons) {
                boolean flag = false;
                switch (tmpButton) {
                    case ACTION_SAVE:
                        flag = true;
                        title = SAVE_BUTTON;
                        break;
                    case ACTION_SUBMIT:
                        flag = true;
                        title = SUBMIT_BUTTON;
                        break;
                    case ACTION_REVOKE:
                        flag = true;
                        title = REVOKE_BUTTON;
                        break;
                    case ACTION_GOTO:
                        flag = true;
                        title = GOTO_BUTTON;
                        break;
                    case ACTION_BACK:
                        flag = true;
                        title = BACK_BUTTON;
                        break;
                }

                if (flag) {
                    result.append(String.format("<button class=\"layui-btn\" name=\"%s\" lay-submit=\"\" lay-filter=\"formCheck\" >%s</button>", title, actionTypeMap.get(tmpButton) == null ? "" : actionTypeMap.get(tmpButton)));
                }
            }
        }
        return result.toString();
    }

    /**
     * 设置<input hiddern...>标签值
     */
    private String getHiddernTag(WfWorkflowInstance wfWorkflowInstance, List<FormElement> arrFormElement) {
        StringBuffer result = new StringBuffer();
        result.append(String.format("<input type=\"hidden\" id=\"wfId\" name=\"wfId\" value=\"%s\">", wfWorkflowInstance.getWfId()));
        result.append(String.format("<input type=\"hidden\" id=\"taskId\" name=\"taskId\" value=\"%s\">", wfWorkflowInstance.getTaskId() == null ? "" : wfWorkflowInstance.getTaskId()));
        result.append(String.format("<input type=\"hidden\" id=\"taskkeyId\" name=\"taskkeyId\" value=\"%s\">", wfWorkflowInstance.getTaskkeyId() == null ? "" : wfWorkflowInstance.getTaskkeyId()));
        result.append(String.format("<input type=\"hidden\" id=\"activityId\" name=\"activityId\" value=\"%s\">", wfWorkflowInstance.getActivityId()));

        for (FormElement tempf : arrFormElement) {
            if (tempf.getObjType() != null && tempf.getObjType().equals("opinion")) {
                result.append(String.format("<input type=\"hidden\" id=\"" + tempf.getName() + "\" name=\"oldopinion\" value=\'%s\'>", tempf.getOldOpinion()));
            }
        }

        return result.toString();
    }

    /**
     * 获取指定正则式的值的一览
     */
    private List<String> getStrings(String str, String regx) {
        //1.将正在表达式封装成对象Patten 类来实现
        Pattern pattern = Pattern.compile(regx);
        //2.将字符串和正则表达式相关联
        Matcher matcher = pattern.matcher(str);
        //3.String 对象中的matches 方法就是通过这个Matcher和pattern来实现的。

        List<String> result = new ArrayList<String>();
        //查找符合规则的子串
        while (matcher.find()) {
            //获取 字符串
            result.add(matcher.group());
            //获取的字符串的首位置和末位置
            //System.out.println(matcher.start()+"--"+matcher.end());
        }
        return result;
    }

    /**
     * 返回双引号之间的值
     */
    private String getDoubleQuotationValue(String value) {
        String result = null;

        if (value == null && value.length() > 0) {
            result = "";
        } else {
            int index = value.indexOf("\"");
            if (index >= 0 && (index + 1) < value.length()) {
                result = value.substring(index + 1, value.length() - 1);
            } else {
                result = "";
            }
        }

        return result;
    }

    /**
     * 获取指定数据字典（假定只有一层的结构）
     */
    private List<WfDictionary> getSysCodes(String value) {
        List<WfDictionary> result = null;

        if (value != null && value.length() > 0) {
            WfDictionary wfDictionary = new WfDictionary();
            wfDictionary.setParentId(value);

            try {
                result = wfDictionaryMapper.selectAll(wfDictionary);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            result = new ArrayList<>();
        }

        return result;
    }

    /**
     * 取得并返回默认值(给默认值设置值)
     */
    public WfDefaultValue getDefaultValue(String value) {
        final String DEFAULT_USER = "1";
        final String DEFAULT_DATETIME = "2";
        final String DEFAULT_NOW = "3";

        final String DEFAULT_OGN = "9";
        final String DEFAULT_ORG = "10";
        final String DEFAULT_DEPMANAGER = "11";

        WfDefaultValue result = new WfDefaultValue();

        SysUser sysUser = UserUtil.getUser();
        SysOrg sysOrg = new SysOrg();
        SysOrg sysOgn = new SysOrg();
        SysPostUser sysPostUser = new SysPostUser();

        sysPostUser.setUserId(sysUser.getId());
        sysPostUser.setMainFlag(1);
        sysPostUser.setState(1);
        sysPostUser = sysPostUser.selectOne(new QueryWrapper<SysPostUser>().setEntity(sysPostUser));

        sysOrg.setId(sysPostUser.getOrgId());
        sysOrg = sysOrg.selectById();

        sysOgn.setId(sysOrg.getOgnId());
        sysOgn = sysOgn.selectById();

        boolean isDefined = false;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        switch (value) {
            case DEFAULT_USER:
                result.setId(sysUser.getId().toString());
                result.setValue(sysUser.getUserName());
                result.setObjectName("SysUser");
                break;
            case DEFAULT_NOW:
                result.setValue(simpleDateFormat.format(new Date()));
                break;
            case DEFAULT_DATETIME:
                result.setValue(sdf.format(new Date()));
                break;
            case DEFAULT_OGN:
                result.setId(sysOgn.getId().toString());
                result.setValue(sysOgn.getOrgName());
                result.setObjectName("ogn");
                break;
            case DEFAULT_ORG:
                result.setId(sysOrg.getId().toString());
                result.setValue(sysOrg.getOrgName());
                result.setObjectName("org");
                break;
            case DEFAULT_DEPMANAGER:
                SysPost sysPost = new SysPost();
                sysPost.setOrgId(sysOrg.getId());
                sysPost.setDutyId(7);
                sysPost = sysPost.selectOne(new QueryWrapper<SysPost>().setEntity(sysPost));

                sysPostUser = new SysPostUser();
                sysPostUser.setOrgId(sysOrg.getId());
                sysPostUser.setPostId(sysPost.getId());
                sysPostUser.setState(1);
                List<SysPostUser> spuList = sysPostUser.selectList(new QueryWrapper<SysPostUser>().setEntity(sysPostUser));

                if(spuList.size() == 1){
                    SysUser su = new SysUser();
                    su.setId(spuList.get(0).getUserId());
                    su = su.selectById();
                    result.setId(su.getId().toString());
                    result.setValue(su.getUserName());
                    result.setObjectName("depManager");
                }else{
                    result.setId("");
                    result.setValue("");
                    result.setObjectName("depManager");
                }

                break;
        }

        return result;
    }
}
